<?php

namespace app\admin\controller;

use app\admin\model\Transaction;
use app\admin\model\user\Balance;
use app\admin\model\user\Extend;
use app\common\library\Reserve as ReserveLib;
use app\admin\model\Setting;
use app\common\controller\Backend;
use app\common\library\Yunding;
use Carbon\Carbon;
use EasyWeChat\Factory;
use think\Db;
use think\Env;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Reserve extends Backend
{

    /**
     * Reserve模型对象
     * @var \app\admin\model\Reserve
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Reserve;
        $this->view->assign("payWayList", $this->model->getPayWayList());
        $this->rechargeBonus = Setting::getSingleSetting('recharge_bonus');
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model->with(['user', 'store', 'room', 'paytransaction', 'paybalance'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            
            // 由于后来增加了组合支付，并且没有之前卡支付小时记录，
            // 所以对于卡支付单独查询记录后计算金额
            // 查找有组合支付的
            $cardIds = [];
            $cardHours = [];
            // 有组合时到对应表查找组合支付了多久
            $reserveIds = [];
            foreach ($list as $row) {
                $cardId = $row->card_id;
                $startParse = Carbon::parse($row->starttime);
                $endParse = Carbon::parse($row->endtime);
                $diffMins = $endParse->diffInMinutes($startParse);
                if (substr($diffMins, -1) == '9') {
                    $diffMins += 1;
                }
                // 转换为小时
                $diffHours = round($diffMins / 60, 1);
                if (!empty($row->card_id)) {
                    // 如果是卡组合支付
                    if (!empty($row->transaction_id)) {
                        $reserveIds[] = $row->id;
                    } else {
                        $cardHours[$row->card_id][] = [
                            'reserve_id' => $row->id,
                            'consume_hours' => $diffHours,
                        ];
                    }
                    $cardIds[] = $cardId;
                }
            }
            if (!empty($reserveIds)) {
                // 查找卡组合支付时所用时长
                $cardPays = \app\admin\model\ReservePays::where('reserve_id', 'in', $reserveIds)->select();
                foreach ($cardPays as $cp) {
                    $cardHours[$cp->pay_id][] = [
                        'reserve_id' => $cp->reserve_id,
                        'consume_hours' => $cp->pay_amount,
                    ];
                }
            }
            $cardConsumers = [];
            $excepReserveIds = [];
            if (!empty($cardIds)) {
                // 查找相关卡的记录
                $userCards = \app\admin\model\user\Card::where('id', 'in', $cardIds)->select();
                foreach ($userCards as $uc) {
                    if (isset($cardHours[$uc->id])) {
                        $price = $uc->price;
                        $totalHour = $uc->total_hour;
                        if ($totalHour > 0) {
                            $perHourPrice = round($uc->price / $totalHour, 2);
                        } else {
                            $perHourPrice = 0;
                        }
                        $hours = $cardHours[$uc->id];
                        foreach($hours as $h) {
                            $cardConsumers[$h['reserve_id']] = round($h['consume_hours'] * $perHourPrice, 2);
                            if ($totalHour == 0) {
                                $excepReserveIds[] = $h['reserve_id'];
                            }
                        }
                    }
                }
            }
           
            // 计算每种支付涉及的金额
            foreach ($list as $row) {
                if ($row->re_status == '1') {
                    $totalFee = 0;
                    if ($row->card_id && isset($cardConsumers[$row->id])) {
                        if (in_array($row->id, $excepReserveIds)) {
                            $row->card_fee = '异常';
                        } else {
                            $row->card_fee = $cardConsumers[$row->id];
                            $totalFee += $cardConsumers[$row->id];
                        }
                    }
                    if ($row->transaction_id) {
                        $row->transaction_fee = $row->paytransaction->fee;
                        $totalFee += $row->paytransaction->fee;
                    }
                    if ($row->balance_id) {
                        $row->balance_fee = round(($row->paybalance->value / (100 + $this->rechargeBonus)) * 100, 2);
                        $totalFee += $row->balance_fee;
                    }
                    if (in_array($row->id, $excepReserveIds)) {
                        $row->total_fee = '异常';
                    } else {
                        $row->total_fee = round($totalFee, 2);
                    }
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function ajaxCancelReserve()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->get('id');
            $reserve = \app\admin\model\Reserve::get($id, ['room']);
            $reserveLib = new ReserveLib();
            $ret = $reserveLib->cancelReserve($reserve->user_id, $reserve);

            if ($ret['code'] < 0) {
                $this->error($ret['msg']);
            }
            $this->success('当前预约取消成功');
        }
    }


}
